import React, { Component } from 'react'
import { Input, Button, List } from 'antd'
import store from '@/store'
import * as action from '@/store/actionCreators'
import { TodoListStyle } from './style'

class TodoList extends Component {
    constructor(props) {
        super(props)
        this.state = store.getState()
        this.handleStoreChange = this.handleStoreChange.bind(this)
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleSub = this.handleSub.bind(this)
        this.handleDel = this.handleDel.bind(this)
        store.subscribe(this.handleStoreChange)
    }
    /**
     * 处理变化的存储
     */
    handleStoreChange() {
        this.setState(store.getState())
    }
    /**
     * 处理文本框变更
     */
    handleInputChange(e) {
        const action = {
            type: 'input-change',
            value: e.target.value
        }
        store.dispatch(action)
    }
    /**
     * 处理提交信息
     */
    handleSub() {
        const action = {
            type: 'add-list'
        }
        store.dispatch(action)
    }
    /**
     * 处理删除
     */
    handleDel(index) {
        const action = {
            type: 'del-list',
            index
        }
        store.dispatch(action)
    }
    render() {
        let { inputValue, todoArray } = this.state
        return (
            <TodoListStyle>
                <header>
                    <label htmlFor="inputId">输入列表内容:</label>
                    <div className="input-box">
                        <Input id="inputId"
                            value={inputValue}
                            onChange={this.handleInputChange} />
                    </div>
                    <Button type="primary" onClick={this.handleSub}>提交</Button>
                </header>
                <main>
                    <List bordered
                        dataSource={todoArray}
                        renderItem={(item, index) => (
                            <List.Item onClick={() => { this.handleDel(index) }}>{item}</List.Item>
                        )}
                    >
                    </List>
                </main>
            </TodoListStyle>
        )
    }
    /**
     * 页面渲染后加载todoList初始数据
     */
    componentDidMount() {
        const act = action.getListInfo()
        store.dispatch(act)
    }
}

export default TodoList